<!--  -->
<script setup>
import SimpleInput from '@/components/input/SimpleInput.vue'
import SubmitBtn from '@/components/button/SubmitBtn.vue'
import { addQuestionAPI, addQuestionWithAnswerAPI } from '@/apis/quest'
import { getAllTagAPI } from '@/apis/tag'
import Tag from '@/components/Tag.vue'
import { ref, nextTick, onMounted } from 'vue'
import { useBreadsStore, useUserStore } from '@/stores'
import Card from '@/components/Card.vue'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const { setBreadCrumbs } = useBreadsStore()
setBreadCrumbs([
  { title: '问题列表', path: '/questions' },
  { title: '新增问题' }
])

const form = ref({
  title: '',
  content: '',
  answer: '',
  tagIds: [],
})
const allTags = ref([])
const suggestionItems = ref([])

onMounted(() => {
  getAllTagAPI().then(res => {
    allTags.value = res.data
  }
  ).catch(() => null)
})

const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const inputRef = ref(null)
const handleClose = id => dynamicTags.value = dynamicTags.value.filter(v => v.id !== id)
const showInput = () => {
  inputVisible.value = true
  suggestionItems.value.length = 0
  nextTick(() => inputRef.value.focus())
}

function closeInput() {
  inputVisible.value = false
  inputValue.value = ''
  suggestionItems.value.length = 0
}

function getSuggestion() {
  if (!inputValue.value) return
  suggestionItems.value = allTags.value.filter(v => v.displayName.includes(inputValue.value))
}

const handleInputConfirm = (v) => {
  dynamicTags.value.push(v)
  inputVisible.value = false
  inputValue.value = ''
}

function submit() {

  const err = _check()
  if (err) {
    alert(err)
    return
  }
  const { id } = userStore.getUserInfo().user
  form.value.tagIds = dynamicTags.value.map(v => v.id)

  if (form.value.answer) {
    addQuestionWithAnswerAPI({ userId: id, ...form.value })
      .then(res => {
        router.push(`/question/${res.data}`)
      })
      .catch(() => null)
  } else {
    addQuestionAPI({ userId: id, ...form.value })
      .then(res => {
        router.push(`/question/${res.data}`)
      })
      .catch(() => null)
  }

  function _check() {
    if (!form.value.title) return '标题不能为空'
    if (form.value.title.length < 5) return '标题不能少于5个字'
    if (!form.value.content) return '内容不能为空'
    if (!dynamicTags.value.length) return '标签不能为空'
    return null
  }
}
</script>

<template>
  <div class="view-container">
    <div class="left-wrapper">

      <h1>新增问题</h1>
      <div class="label">标题 <span class="desc">大于五个字</span></div>
      <SimpleInput v-model="form.title" />
      <div class="label">内容 <span class="desc">大于五个字</span></div>
      <textarea v-model="form.content"></textarea>
      <div class="label">标签 <span class="desc">至少一个</span></div>
      <div class="tag-container">
        <Tag v-for="tag in dynamicTags" :key="tag" @onClose="() => handleClose(tag.id)">
          {{ tag.displayName }}
        </Tag>
        <div v-if="inputVisible" class="input-container">
          <input ref="inputRef" v-model="inputValue" class="tag-input" @input="getSuggestion" />
          <Icon @click="closeInput" icon-name="cancel"></Icon>

          <div class=" suggestion">
            <span @click="handleInputConfirm(v)" class="suggestion-item" v-for="v in suggestionItems" :key="v.id">
              {{ v.displayName }}
            </span>
          </div>
        </div>
        <SubmitBtn v-else style="padding: 0 4px;height: 100%;" @click="showInput">+ New Tag</SubmitBtn>
      </div>
      <div class="label">回答自己的问题 <span class="desc">即直接给出答案</span></div>
      <textarea v-model="form.answer"></textarea>
      <div class="form-btn">
        <SubmitBtn @click="submit">提交</SubmitBtn>
      </div>
    </div>
    <div class="right-wrapper">
      <Card topic="如何排版">
        无
      </Card>
    </div>
  </div>

</template>

<style scoped lang="scss">
.view-container {
  display: flex;
  justify-content: space-between;
  min-height: 100%;
}

.left-wrapper {
  margin-right: 1em;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;

  .label {
    font-size: 1.2rem;
    color: var(--text-02);

    .desc {
      font-size: 0.8rem;
      color: #979797;
    }
  }

  .form-btn {
    display: flex;
    margin-top: 2em;
    justify-content: flex-end !important;
  }

  input,
  textarea {
    padding: 4px 11px;
    font-size: 14px;
    line-height: 1.5;
    color: #444c3f;
    outline: none;
    border: 1px solid #9cb294;
    background-color: var(--bgc-02);
    border-radius: 2px;
  }

  textarea {
    min-height: 200px;
    height: auto;
    resize: vertical;
  }
}

.right-wrapper {
  position: relative;
  width: 300px;
  border-left: 1px dashed var(--border-secondary);
  padding: 0 1em;
}

.tag-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  height: 25px;

  .input-container {
    height: 100%;
  }

  .tag-input {
    width: 120px;
    height: 100%;
    outline: none;
    font-size: 14px;
    padding: 1px .5em;
    color: inherit;
    background-color: var(--bgc-02);
    border: 1px solid var(--border-primary);
    border-radius: 2px;

    &:hover {
      border-color: #4d9f00;
    }

  }

  .icon {
    position: relative;
    right: 20px;
    top: 2px;

    &:hover {
      background-color: #ca0000;
    }
  }

  .suggestion {
    position: absolute;
    background-color: var(--bgc-02);
    border: 1px solid var(--border-primary);
    border-radius: 2px;
    margin-top: 4px;
    z-index: 10;
    max-width: 300px;
    display: flex;
    flex-wrap: wrap;

    .suggestion-item {
      padding: 4px 11px;
      font-size: 14px;
      cursor: pointer;

      &:hover {
        background-color: #cce1b8;
      }
    }
  }
}
</style>
